package com.ruoyi.dm.component;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.CollectFileTypeConstants;
import com.ruoyi.common.utils.biz.BizModule;
import com.ruoyi.common.utils.biz.PathUtil;
import com.ruoyi.dm.domain.po.AirCollectRecordPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;

/**
 * 空间 密度数据策略 风云3c
 */
@Component
@Slf4j
public class FY3CDataStrategy implements DataStrategy<AirCollectRecordPO> {

    @Override
    public AirCollectRecordPO makeupPo(AirCollectRecordPO po) {

        String fileName = po.getFileName();
        //FY3C_GNOSX_GBAL_L2_ADP_MLT_NUL_20140601_0003_G16XX_MS.NC
        String[] split = fileName.split("_");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate parse = LocalDate.parse(split[7], formatter);
        po.setFileDate(parse);
        return po;
    }

    @Override
    public String pythonCmd(String satellite, String dataType, String filePath, String method, Integer year) {
        String fileType = CollectFileTypeConstants.TYPE_DEN;
        String outPath = PathUtil.outputModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result") + "/" + fileType;
        FileUtil.mkdir(outPath);
        String logPath = PathUtil.tmpModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result") + "/" + fileType;
        FileUtil.mkdir(logPath);
        String script = PathUtil.codeModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("fy3cScript");
        String tmpPath = PathUtil.tmpModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result");
        File inputFile = new File(tmpPath, new File(filePath).getName() + ".json");
        //将参数写入文件
        LinkedHashMap<String, Object> object = new LinkedHashMap<>();
        //必需按这个顺序
        object.put("file_path", filePath);
        object.put("output_path", outPath);
        //这些参数是固定的
        object.put("threshold_density", 2.5);
        object.put("threshold_altitude", 1.2);
        String param = JSON.toJSONString(object);
        FileUtil.writeString(param, inputFile, StandardCharsets.UTF_8);
        String[] cmdLines = new String[3];
        cmdLines[0] = "python";
        cmdLines[1] = script;
        cmdLines[2] = inputFile.getAbsolutePath();
        String commond = ArrayUtil.join(cmdLines, " ");
        log.info("拼接脚本:{},{}", commond, param);
        return commond;
    }
}
